package com.glsc.ngateway.platform.controller.glres;


import com.glsc.ngateway.common.api.common.utils.JsonUtil;
import com.glsc.ngateway.common.api.flowable.dto.demand.FileType;
import com.glsc.ngateway.common.api.flowable.dto.demand.ReportShowResponse;
import com.glsc.ngateway.common.api.platform.dto.user.PlatformUserDto;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.glres.GlscSystemFile;
import com.glsc.ngateway.platform.aspect.UserCache;
import com.glsc.ngateway.platform.dto.GlscSystemFileDto;
import com.glsc.ngateway.platform.service.glres.GlscSystemFileService;
import com.glsc.ngateway.platform.utils.TokenUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 资源管理-系统用户权限
 */
@RestController
@RequestMapping("/api/res/system/file")
@Slf4j
public class GlscSystemFileController {

    @Resource
    private UserCache userCache;

    @Resource
    private GlscSystemFileService glscSystemFileService;

    @Autowired
    TokenUtil tokenUtil;

    @Value("${file.systemResFileDownloadUrl}")
    String downloadUrl = "";

    /**
     * 分页查找
     *
     * @param dto
     * @param request
     * @return
     */
    @PostMapping("/page")
    public PlatformResponse<Page<GlscSystemFile>> page(@RequestBody GlscSystemFileDto dto, HttpServletRequest request) {

        Map<String, Object> param = new HashMap<>();
        if (StringUtils.isNotBlank(dto.getFileName())) {
            param.put("LIKE_fileName", dto.getFileName());
        }

        if (Objects.isNull(dto.getSystemId())) {
            PlatformResponse.successData(Page.empty());
        }
        param.put("EQ_systemId", dto.getSystemId());

        param.put("EQ_fileType", dto.getFileType());

        param.put("EQ_sourceType", dto.getSourceType());

        Page<GlscSystemFile> page = glscSystemFileService.page(dto.getPageNo(), dto.getPageSize(), param);
        return PlatformResponse.successData(page);
    }

    /**
     * 根据id查找
     *
     * @param
     * @return
     */
    @GetMapping("/findById")
    public PlatformResponse<GlscSystemFile> findById(@ApiParam(required = false, value = "id") @RequestParam(required = true) Integer id) {
        return PlatformResponse.successData(glscSystemFileService.findById(id));
    }

    /**
     * 保存
     *
     * @return
     */
    @PostMapping("/upload")
    public PlatformResponse<?> upload(MultipartFile file, Integer id, HttpServletRequest request) {
        PlatformUserDto user = userCache.get(request);
        return glscSystemFileService.upload(file, id, user);
    }

    @PostMapping("/save")
    public PlatformResponse<?> save(@RequestBody GlscSystemFile file, HttpServletRequest request) {
        PlatformUserDto user = userCache.get(request);
        file.setUserName(user.getName());
        file.setUserId(user.getId());
        glscSystemFileService.save(file);
        return PlatformResponse.success();
    }


    /**
     * 根据地删除
     *
     * @param obj
     * @return
     */
    @PostMapping("/delete")
    public PlatformResponse<?> delete(@RequestBody GlscSystemFile obj) {
        glscSystemFileService.delete(obj.getId());
        return PlatformResponse.success();
    }


    /**
     * 下载
     *
     * @param fileId
     * @return
     * @throws IOException
     */
    @GetMapping("/getContentById")
    @ApiOperation(value = "根据fileId下载文件", notes = "根据fileId下载文件")
    public byte[] download(@ApiParam(required = true, value = "fileId") @RequestParam Integer fileId, HttpServletResponse response) throws IOException {

        GlscSystemFile file = glscSystemFileService.findById(fileId);
        Assert.isTrue(Objects.nonNull(file), "文件不存在");

        HttpHeaders headers = new HttpHeaders();
        ResponseEntity<byte[]> entity = null;
        InputStream in = null;
        in = new FileInputStream(new File(file.getFilePath()));
        byte[] bytes = new byte[in.available()];
        String imageName = file.getFileName();
        //处理IE下载文件的中文名称乱码的问题
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) attrs).getRequest();
        String header = request.getHeader("User-Agent").toUpperCase();
        if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
            imageName = URLEncoder.encode(imageName, "utf-8");
            imageName = imageName.replace("+", "%20"); //IE下载文件名空格变+号问题
        } else {
            //imageName = new String(imageName.getBytes(), "UTF-8");
            imageName = URLEncoder.encode(imageName, "utf-8");
        }
        in.read(bytes);
        //headers.add("Content-Disposition", "attachment;filename=" + imageName);

        response.setContentType("APPLICATION/OCTET-STREAM");
        response.setHeader("Content-Disposition", "attachment;filename=" + imageName);
        return bytes;
    }

    /**
     * 预览
     *
     * @param fileId
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/showDoc")
    public PlatformResponse<ReportShowResponse> show(@ApiParam(required = true, value = "文件ID") @RequestParam Integer fileId) {

        GlscSystemFile file = glscSystemFileService.findById(fileId);

        PlatformResponse<ReportShowResponse> ret = null;
        try {
            String title = file.getFileName();
            String url = downloadUrl + fileId;
            String token = tokenUtil.generateToken(JsonUtil.Obj2Str(new ReportShowResponse(title, url, FileType.valueOf(title.substring(title.lastIndexOf(".") + 1)))));

            ReportShowResponse resdata = new ReportShowResponse(title, url, token, FileType.valueOf(title.substring(title.lastIndexOf(".") + 1)));
            ret = PlatformResponse.successData(resdata);

            ret.setFileId(title);
        } catch (Exception e) {
            ret = PlatformResponse.failedMsg(e.getMessage(), e.getMessage());
        }

        return ret;
    }


}
